package mis.ds.ps.ui;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;

public class Step1 extends JPanel implements ActionListener {
	
	private static final long serialVersionUID = 1L;	
	private JTextField txtFile,txtId,txtValue;
	private JButton btnOpenFile, btnSaveMapper;
	private JTree treeMapper;
	private JLabel jLabel1,jLabel2,jLabel3;
	private JComboBox cmbMapper;
	
	private JFileChooser fc;
	private JScrollPane jScrollPane1;
	private JPanel jPanel1;
	
	private Frame parentFrame;
	
	UiFacade mp = new UiFacade();
    List<String> mapperList = null;
    Map<String,Map<String,Object>> hashEntidades = null;
	
	public Step1(/*Frame parentFrame*/) {
//		this.parentFrame = parentFrame;
		initialize();		
	}
	
	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		txtFile = new JTextField(50);
		btnOpenFile = new JButton("Open File...");
		btnOpenFile.setToolTipText("Open File.......");					
		fc = new JFileChooser();
		
		jLabel1 = new JLabel("Mapper: ");
		cmbMapper = new JComboBox();
		fillComboMappers();
		
		treeMapper = new JTree();
		treeMapper.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                treeMapperValueChanged(evt);
            }
        });
		buildMapper(null);
		
		//Create the scroll pane and add the tree to it. 
//        JScrollPane treeView = new JScrollPane(treeMapper);
		jScrollPane1 = new JScrollPane();
		jScrollPane1.setViewportView(treeMapper);
        
		jLabel2 = new JLabel("Id");
        txtId = new JTextField(20);
        jLabel3 = new JLabel("Value");
        txtValue = new JTextField(20);
        
		
		btnSaveMapper = new JButton("Save Mapper");

		btnOpenFile.addActionListener(this);
		cmbMapper.addActionListener(this);
		
		btnSaveMapper.addActionListener(this);
		
//		add(txtFile);
//		add(btnOpenFile);
//		add(jLabel1);
//		add(cmbMapper);
//		add(btnSaveMapper);
//		add(treeMapper);
//		add(jLabel2);
//		add(txtId);
//		add(jLabel3);
//		add(txtValue);

		
		jPanel1 = new JPanel();
		jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Details"));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txtValue, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)
                    .addComponent(txtId, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtFile, javax.swing.GroupLayout.PREFERRED_SIZE, 514, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 103, Short.MAX_VALUE)
                        .addComponent(btnOpenFile, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmbMapper, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btnSaveMapper)
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtFile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnOpenFile))
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cmbMapper, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSaveMapper))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(31, Short.MAX_VALUE))
        );
	}
	
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnOpenFile) {
			int returnval = fc.showOpenDialog(Step1.this);
			
			if (returnval == JFileChooser.APPROVE_OPTION) {
				File file = fc.getSelectedFile();
				
				txtFile.setText(file.getName());
			}
		} else if (e.getSource() == cmbMapper) {
			hashEntidades = mp.useMapper(cmbMapper.getSelectedItem().toString());
		} else if (e.getSource() == btnSaveMapper) {
//			JDialog dlgMapper = new frmMapper(new ImportForm(), true);
//			
//			dlgMapper.setVisible(true);
			
			
//			System.err.println("Opening dialog.");
//            DlgMapper myDialog = new DlgMapper(parentFrame, true, "Do you like Java?");
//            System.err.println("After opening dialog.");
//            if(myDialog.getAnswer()) {
//                System.err.println("The answer stored in CustomDialog is 'true' (i.e. user clicked yes button.)");
//            }
//            else {
//                System.err.println("The answer stored in CustomDialog is 'false' (i.e. user clicked no button.)");
//            }
		}
    }
	
	public void fillComboMappers() {
		mapperList = mp.getMappersList();
		
        
        Iterator<String> i = mapperList.iterator();
        while(i.hasNext()) {
            String item = (String) i.next();
            //System.out.println("Item: " + item);
            cmbMapper.addItem(item);
        }
	}
	
	public void buildMapper(String name) {
		hashEntidades = mp.useMapper(name);
        
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("TimeTable");        
        
        DefaultMutableTreeNode entidade, atributo;
        
        Set setEntidades = hashEntidades.entrySet();         
        
        Iterator j = setEntidades.iterator();


        while(j.hasNext()){
            Map.Entry me = (Map.Entry) j.next();
//            System.out.println(me.getKey() + " : " + me.getValue() );

            entidade = new DefaultMutableTreeNode(me.getKey());
            root.add(entidade);
            
            HashMap<String,String> hashAtributos = (HashMap<String,String>) me.getValue();
            
            Set setAtributos = hashAtributos.entrySet();         
        
            Iterator k = setAtributos.iterator();
            
            while(k.hasNext()) {
                Map.Entry meAtr = (Map.Entry) k.next();
                
                atributo = new DefaultMutableTreeNode(meAtr.getKey() + "-" + meAtr.getValue());
                entidade.add(atributo);
            }
        }

        DefaultTreeModel treeModel = new DefaultTreeModel(root);

        treeMapper.setModel(treeModel);
        treeMapper.getSelectionModel().setSelectionMode(
                TreeSelectionModel.SINGLE_TREE_SELECTION);
	}
	
	private void treeMapperValueChanged(TreeSelectionEvent evt) {                                        
        // TODO add your handling code here:
//        TreePath[] paths = treeMapper.getSelectionPaths();
//        System.out.print(paths.toString());
        
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) 
                treeMapper.getLastSelectedPathComponent();

        if (node == null) return;

        Object nodeInfo = node.getUserObject();
        if (node.isLeaf()) {
            //System.out.println(nodeInfo.toString());
            
            String[] valores = nodeInfo.toString().split("-");
            
            txtId.setText(valores[0]);
            
            if (valores.length>1)
                txtValue.setText(valores[1]);
            else
                txtValue.setText("");
        }
    }
}
